//
//  MainViewController.swift
//  ScarnKing
//
//  Created by ninebot on 2025/7/22.
//

import UIKit

class MainViewController: UIViewController {
    
    // MARK: - UI Components
    private let scrollView = UIScrollView()
    private let contentView = UIView()
    
    private let headerView = UIView()
    private let titleLabel = UILabel()
    private let titleUnderline = UIView()
    
    private let featureIconsView = UIView()
    private let featureIconsCollectionView: UICollectionView
    
    private let recommendedSection = UIView()
    private let recommendedLabel = UILabel()
    private let recommendedButtonsStackView = UIStackView()
    

    
    // MARK: - Data Models
    struct FeatureIcon {
        let icon: String
        let title: String
    }
    
    private let featureIcons: [FeatureIcon] = [
        FeatureIcon(icon: "icon_ocr", title: "OCR识别"),
        FeatureIcon(icon: "icon_doc", title: "文档扫描"),
        FeatureIcon(icon: "icon_transfor", title: "AI翻译"),
        FeatureIcon(icon: "icon_distance", title: "手机测距"),
        FeatureIcon(icon: "icon_photo", title: "老照片")
    ]
    
    // 推荐功能按钮的图片名称数组
    private let recommendedButtonImages: [String] = [
        "card_ocr",
        "card_doc", 
        "card_ai_transfor",
        "card_distance",
        "card_photo_review"
    ]
    

    
    // MARK: - Initialization
    override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: Bundle?) {
        // 设置功能图标的布局
        let featureIconsLayout = UICollectionViewFlowLayout()
        featureIconsLayout.scrollDirection = .horizontal
        featureIconsLayout.minimumInteritemSpacing = 20
        featureIconsLayout.minimumLineSpacing = 0
        featureIconsLayout.sectionInset = UIEdgeInsets(top: 0, left: 20, bottom: 0, right: 20)
        
        featureIconsCollectionView = UICollectionView(frame: .zero, collectionViewLayout: featureIconsLayout)
        
        super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil)
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    // MARK: - Lifecycle
    override func viewDidLoad() {
        super.viewDidLoad()
        setupUI()
        setupConstraints()
    }
    
    // MARK: - UI Setup
    private func setupUI() {
        updateTheme()
        
        // 设置页面背景色
        let isDark = ThemeManager.shared.isDarkMode
        view.backgroundColor = isDark ? ThemeManager.Colors.background(for: isDark) : kAppColor
        
        setupHeaderView()
        setupFeatureIcons()
        setupRecommendedSection()
        setupScrollView()
        
        // 监听主题变化
        NotificationCenter.default.addObserver(self, selector: #selector(themeDidChange), name: .themeDidChange, object: nil)
    }
    
    private func setupHeaderView() {
        let isDark = ThemeManager.shared.isDarkMode
        titleLabel.text = "智能扫描仪"
        titleLabel.font = UIFont.boldSystemFont(ofSize: 28)
        titleLabel.textColor = ThemeManager.Colors.text(for: isDark)
        
        titleUnderline.backgroundColor = .systemBlue
        titleUnderline.layer.cornerRadius = 2
        
        headerView.addSubview(titleLabel)
        headerView.addSubview(titleUnderline)
    }
    
    private func setupFeatureIcons() {
        featureIconsCollectionView.backgroundColor = .clear
        featureIconsCollectionView.showsHorizontalScrollIndicator = false
        featureIconsCollectionView.showsVerticalScrollIndicator = false
        featureIconsCollectionView.isScrollEnabled = true
        featureIconsCollectionView.delegate = self
        featureIconsCollectionView.dataSource = self
        featureIconsCollectionView.register(FeatureIconCell.self, forCellWithReuseIdentifier: "FeatureIconCell")
        
        featureIconsView.addSubview(featureIconsCollectionView)
    }
    

    
    private func setupRecommendedSection() {
        let isDark = ThemeManager.shared.isDarkMode
        recommendedLabel.text = "   推荐功能"
        recommendedLabel.font = UIFont.boldSystemFont(ofSize: 20)
        recommendedLabel.textColor = ThemeManager.Colors.text(for: isDark)
        
        // 设置堆栈视图
        recommendedButtonsStackView.axis = .vertical
        recommendedButtonsStackView.spacing = 10
        recommendedButtonsStackView.distribution = .fillEqually
        
        // 创建第一行（2个按钮）
        let firstRowStack = UIStackView()
        firstRowStack.axis = .horizontal
        firstRowStack.spacing = 16
        firstRowStack.distribution = .equalCentering
        firstRowStack.layoutMargins = UIEdgeInsets(top: 0, left: 16, bottom: 0, right: 0)
        firstRowStack.isLayoutMarginsRelativeArrangement = true
        
        // 创建第二行（2个按钮）
        let secondRowStack = UIStackView()
        secondRowStack.axis = .horizontal
        secondRowStack.spacing = 16
        secondRowStack.distribution = .equalCentering
        secondRowStack.layoutMargins = UIEdgeInsets(top: 0, left: 16, bottom: 0, right: 0)
        secondRowStack.isLayoutMarginsRelativeArrangement = true
        
        // 创建第三行（1个按钮，居中）
        let thirdRowStack = UIStackView()
        thirdRowStack.axis = .horizontal
        thirdRowStack.distribution = .equalCentering
        
        // 创建5个按钮
        for i in 0..<5 {
            let button = UIButton()
            button.backgroundColor = .clear
            button.layer.cornerRadius = 8
            button.tag = i
            
            // 设置按钮图片
            if i < recommendedButtonImages.count {
                button.setBackgroundImage(UIImage(named: recommendedButtonImages[i]), for: .normal)
                button.setBackgroundImage(UIImage(named: recommendedButtonImages[i]), for: .highlighted)
                button.imageView?.contentMode = .scaleAspectFill
            }
            
            // 设置按钮宽度，高度自适应
            button.widthAnchor.constraint(equalToConstant: 170).isActive = true
            
            // 添加点击事件
            button.addTarget(self, action: #selector(recommendedButtonTapped(_:)), for: .touchUpInside)
            
            // 添加到对应的行
            if i < 2 {
                firstRowStack.addArrangedSubview(button)
            } else if i < 4 {
                secondRowStack.addArrangedSubview(button)
            } else {
                thirdRowStack.addArrangedSubview(button)
            }
        }
        
        // 添加所有行到主堆栈视图
        recommendedButtonsStackView.addArrangedSubview(firstRowStack)
        recommendedButtonsStackView.addArrangedSubview(secondRowStack)
        recommendedButtonsStackView.addArrangedSubview(thirdRowStack)
        
        recommendedSection.addSubview(recommendedLabel)
        recommendedSection.addSubview(recommendedButtonsStackView)
    }
    

    
    private func setupScrollView() {
        scrollView.showsVerticalScrollIndicator = true
        
        contentView.addSubview(featureIconsView)
        contentView.addSubview(recommendedSection)
        
        scrollView.addSubview(contentView)
        view.addSubview(scrollView)
        view.addSubview(headerView)
    }
    

    
    // MARK: - Constraints
    private func setupConstraints() {
        scrollView.translatesAutoresizingMaskIntoConstraints = false
        contentView.translatesAutoresizingMaskIntoConstraints = false
        headerView.translatesAutoresizingMaskIntoConstraints = false
        titleLabel.translatesAutoresizingMaskIntoConstraints = false
        titleUnderline.translatesAutoresizingMaskIntoConstraints = false
        featureIconsView.translatesAutoresizingMaskIntoConstraints = false
        featureIconsCollectionView.translatesAutoresizingMaskIntoConstraints = false
        recommendedSection.translatesAutoresizingMaskIntoConstraints = false
        recommendedLabel.translatesAutoresizingMaskIntoConstraints = false
        recommendedButtonsStackView.translatesAutoresizingMaskIntoConstraints = false
        
        NSLayoutConstraint.activate([
            // ScrollView
            scrollView.topAnchor.constraint(equalTo: headerView.bottomAnchor, constant: 20),
            scrollView.leadingAnchor.constraint(equalTo: view.leadingAnchor),
            scrollView.trailingAnchor.constraint(equalTo: view.trailingAnchor),
            scrollView.bottomAnchor.constraint(equalTo: view.safeAreaLayoutGuide.bottomAnchor),
            
            // ContentView
            contentView.topAnchor.constraint(equalTo: scrollView.topAnchor),
            contentView.leadingAnchor.constraint(equalTo: scrollView.leadingAnchor),
            contentView.trailingAnchor.constraint(equalTo: scrollView.trailingAnchor),
            contentView.bottomAnchor.constraint(equalTo: scrollView.bottomAnchor),
            contentView.widthAnchor.constraint(equalTo: scrollView.widthAnchor),
            
            // HeaderView
            headerView.topAnchor.constraint(equalTo: view.safeAreaLayoutGuide.topAnchor, constant: 20),
            headerView.leadingAnchor.constraint(equalTo: view.leadingAnchor, constant: 20),
            headerView.trailingAnchor.constraint(equalTo: view.trailingAnchor, constant: -20),
            
            titleLabel.topAnchor.constraint(equalTo: headerView.topAnchor),
            titleLabel.leadingAnchor.constraint(equalTo: headerView.leadingAnchor),
            
            titleUnderline.topAnchor.constraint(equalTo: titleLabel.bottomAnchor, constant: 4),
            titleUnderline.leadingAnchor.constraint(equalTo: headerView.leadingAnchor),
            titleUnderline.widthAnchor.constraint(equalToConstant: 60),
            titleUnderline.heightAnchor.constraint(equalToConstant: 4),
            titleUnderline.bottomAnchor.constraint(equalTo: headerView.bottomAnchor),
            
            // FeatureIcons
            featureIconsView.topAnchor.constraint(equalTo: contentView.topAnchor, constant: 20),
            featureIconsView.leadingAnchor.constraint(equalTo: contentView.leadingAnchor, constant: 20),
            featureIconsView.trailingAnchor.constraint(equalTo: contentView.trailingAnchor, constant: -20),
            featureIconsView.heightAnchor.constraint(equalToConstant: 100),
            
            featureIconsCollectionView.topAnchor.constraint(equalTo: featureIconsView.topAnchor),
            featureIconsCollectionView.leadingAnchor.constraint(equalTo: featureIconsView.leadingAnchor),
            featureIconsCollectionView.trailingAnchor.constraint(equalTo: featureIconsView.trailingAnchor),
            featureIconsCollectionView.bottomAnchor.constraint(equalTo: featureIconsView.bottomAnchor),
            
            // RecommendedSection
            recommendedSection.topAnchor.constraint(equalTo: featureIconsView.bottomAnchor, constant: 30),
            recommendedSection.leadingAnchor.constraint(equalTo: contentView.leadingAnchor),
            recommendedSection.trailingAnchor.constraint(equalTo: contentView.trailingAnchor, constant: -20),
            recommendedSection.bottomAnchor.constraint(equalTo: contentView.bottomAnchor, constant: -20),
            
            recommendedLabel.topAnchor.constraint(equalTo: recommendedSection.topAnchor),
            recommendedLabel.leadingAnchor.constraint(equalTo: recommendedSection.leadingAnchor),
            
            recommendedButtonsStackView.topAnchor.constraint(equalTo: recommendedLabel.bottomAnchor, constant: 16),
            recommendedButtonsStackView.leadingAnchor.constraint(equalTo: recommendedSection.leadingAnchor),
            recommendedButtonsStackView.trailingAnchor.constraint(equalTo: recommendedSection.trailingAnchor),
            recommendedButtonsStackView.bottomAnchor.constraint(equalTo: recommendedSection.bottomAnchor)
        ])
    }
    
    // MARK: - Actions
    @objc private func featureIconTapped(_ index: Int) {
        print("Feature icon tapped: \(featureIcons[index].title)")
        if index == 0 {
            let vc = SKTakePhotoViewController()
            self.navigationController?.pushViewController(vc, animated: true)
        } else if index == 1 {
            let vc = DocumentScannerViewController()
            self.navigationController?.pushViewController(vc, animated: true)
        } else if index == 2 {
            let vc = TranslationViewController()
            self.navigationController?.pushViewController(vc, animated: true)
        } else if index == 3 {
            let vc = ARDistanceViewController()
            self.navigationController?.pushViewController(vc, animated: true)
        } else if index == 4 {
            let vc = PhotoRestorationViewController()
            self.navigationController?.pushViewController(vc, animated: true)
        }
    }
    
    @objc private func recommendedButtonTapped(_ sender: UIButton) {
        print("Recommended button tapped: \(sender.tag)")
        
        switch sender.tag {
        case 0: // OCR识别
            let vc = SKTakePhotoViewController()
            self.navigationController?.pushViewController(vc, animated: true)
        case 1: // 文档扫描
            let vc = DocumentScannerViewController()
            self.navigationController?.pushViewController(vc, animated: true)
        case 2: // AI翻译
            let vc = TranslationViewController()
            self.navigationController?.pushViewController(vc, animated: true)
        case 3: // AR测距
            let vc = ARDistanceViewController()
            self.navigationController?.pushViewController(vc, animated: true)
        case 4: // 老照片修复
            let vc = PhotoRestorationViewController()
            self.navigationController?.pushViewController(vc, animated: true)
        default:
            break
        }
    }
    
    @objc private func themeDidChange() {
        // 更新页面背景色
        let isDark = ThemeManager.shared.isDarkMode
        view.backgroundColor = isDark ? ThemeManager.Colors.background(for: isDark) : kAppColor
        
        // 重新设置UI以适配新主题
        setupHeaderView()
        setupRecommendedSection()
        
        // 刷新CollectionView以更新文字颜色
        featureIconsCollectionView.reloadData()
    }
    
    // MARK: - Navigation
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        
        // 隐藏导航栏
        navigationController?.setNavigationBarHidden(true, animated: false)
    }
    
    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
        
        // 显示导航栏（当离开页面时）
        navigationController?.setNavigationBarHidden(false, animated: false)
    }
    
    override var preferredStatusBarStyle: UIStatusBarStyle {
        return ThemeManager.shared.isDarkMode ? .lightContent : .darkContent
    }
    

    

    

}

// MARK: - UICollectionViewDataSource & UICollectionViewDelegate
extension MainViewController: UICollectionViewDataSource, UICollectionViewDelegate, UICollectionViewDelegateFlowLayout {
    
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return featureIcons.count
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "FeatureIconCell", for: indexPath) as! FeatureIconCell
        let feature = featureIcons[indexPath.item]
        cell.configure(with: feature)
        
        // 更新文字颜色以适配当前主题
        let isDark = ThemeManager.shared.isDarkMode
        cell.updateTextColor(ThemeManager.Colors.text(for: isDark))
        
        return cell
    }
    
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
        return CGSize(width: 80, height: 100)
    }
    
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        featureIconTapped(indexPath.item)
    }
}

// MARK: - FeatureIconCell
class FeatureIconCell: UICollectionViewCell {
    
    private let iconImageView = UIImageView()
    private let titleLabel = UILabel()
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        setupUI()
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    private func setupUI() {
        iconImageView.contentMode = .scaleAspectFit
        iconImageView.layer.cornerRadius = 30
        iconImageView.clipsToBounds = true
        
        titleLabel.font = UIFont.boldSystemFont(ofSize: 14)
        let isDark = ThemeManager.shared.isDarkMode
        titleLabel.textColor = ThemeManager.Colors.text(for: isDark)
        titleLabel.textAlignment = .center
        
        contentView.addSubview(iconImageView)
        contentView.addSubview(titleLabel)
        
        iconImageView.translatesAutoresizingMaskIntoConstraints = false
        titleLabel.translatesAutoresizingMaskIntoConstraints = false
        
        NSLayoutConstraint.activate([
            iconImageView.topAnchor.constraint(equalTo: contentView.topAnchor),
            iconImageView.centerXAnchor.constraint(equalTo: contentView.centerXAnchor),
            iconImageView.widthAnchor.constraint(equalToConstant: 60),
            iconImageView.heightAnchor.constraint(equalToConstant: 60),
            
            titleLabel.topAnchor.constraint(equalTo: iconImageView.bottomAnchor, constant: 8),
            titleLabel.centerXAnchor.constraint(equalTo: contentView.centerXAnchor),
            titleLabel.bottomAnchor.constraint(equalTo: contentView.bottomAnchor)
        ])
    }
    
    func configure(with feature: MainViewController.FeatureIcon) {
        iconImageView.image = UIImage(named: feature.icon)
        titleLabel.text = feature.title
    }
    
    func updateTextColor(_ color: UIColor) {
        titleLabel.textColor = color
    }
}

 
